iT邦幫忙

0

解LeetCode的學習筆記Day36_Valid Sudoku

LFI 2025-10-27 22:40:36158 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第三十六天

第三十六題題目:Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.

判斷9x9數獨是否有效,只有已填充的格子需要根據以下規則進行驗證:

  1. 每行必須包含不重複的數字 1-9
  2. 每列必須包含不重複的數字 1-9
  3. 3x3九宮格中必須包含不重複的數字 1-9

注意:

  • 數獨(部分填充)可能有效,但不一定可解
  • 只有已填入的格子才需要根據上述規則進行驗證

解題思路

遍歷行,將數字儲存至串列中,判斷串列和集合(把串列轉成集合)個數是否相同,如果不同,代表該行有重複元素,直接回傳False,表示該數獨無效,列、九宮格同理

程式碼

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        for i in range(9):
            row_nums = []
            col_nums = []
            for j in range(9):
                if board[i][j] != ".":
                    row_nums.append(board[i][j])
                if board[j][i] != ".":
                    col_nums.append(board[j][i])
            if len(row_nums) != len(set(row_nums)):
                return False
            if len(col_nums) != len(set(col_nums)):
                return False
        for block_row in range(3):
            for block_col in range(3):
                nine_nums = []
                for i in range(3):
                    for j in range(3):
                        row = block_row * 3 + i
                        col = block_col * 3 + j
                        if board[row][col] != ".":
                            nine_nums.append(board[row][col])
                if len(nine_nums) != len(set(nine_nums)):
                    return False
        return True

這題比較簡單,只是判斷數獨有無效,只要檢查是否有重複項即可


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言